// 全局变量
let orderId = null;
let orderInfo = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    
    // 初始化页面
    initPage();
});

// 初始化页面
function initPage() {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 未登录，跳转到登录页
        window.location.href = './login.html?redirect=' + encodeURIComponent(window.location.href);
        return;
    }
    
    // 获取订单ID
    const urlParams = new URLSearchParams(window.location.search);
    orderId = urlParams.get('id');
    
    if (!orderId) {
        // 没有订单ID，返回订单列表页
        layui.use('layer', function() {
            const layer = layui.layer;
            layer.msg('订单信息不存在', {icon: 0});
            setTimeout(() => {
                window.location.href = './order.html';
            }, 1500);
        });
        return;
    }
    
    // 加载订单信息
    loadOrderDetail();
}

// 加载订单详情
function loadOrderDetail() {
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        ApiService.order.getOrderDetail(orderId)
            .then(response => {
                layer.close(loadingIndex);
                
                if (response.data) {
                    orderInfo = response.data;
                    
                    // 渲染订单状态
                    renderOrderStatus();
                    
                    // 渲染订单进度
                    renderOrderProgress();
                    
                    // 渲染收货信息
                    renderAddressInfo();
                    
                    // 渲染商品信息
                    renderProductList();
                    
                    // 渲染订单信息
                    renderOrderInfo();
                    
                    // 渲染订单金额
                    renderOrderAmount();
                } else {
                    layer.msg('订单信息不存在', {icon: 0});
                    setTimeout(() => {
                        window.location.href = './order.html';
                    }, 1500);
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("获取订单详情失败:", error);
                layer.msg('获取订单详情失败，请重试', {icon: 2});
            });
    });
}

// 渲染订单状态
function renderOrderStatus() {
    const statusTextElement = document.getElementById('statusText');
    const statusDescElement = document.getElementById('statusDesc');
    const statusActionsElement = document.getElementById('statusActions');
    
    // 设置状态文本
    const statusText = getStatusText(orderInfo.status);
    statusTextElement.textContent = statusText;
    
    // 设置状态描述
    let statusDesc = '';
    switch(orderInfo.status) {
        case '待付款':
            statusDesc = `请在 ${formatDate(orderInfo.expireTime)} 前完成支付，超时订单将自动取消`;
            break;
        case '已付款':
            statusDesc = '商家正在处理您的订单，请耐心等待发货';
            break;
        case '已发货':
            statusDesc = `商品已发货，请注意查收`;
            break;
        case '已完成':
            statusDesc = '交易已完成，感谢您的购买';
            break;
        case '已取消':
            statusDesc = '订单已取消';
            break;
        default:
            statusDesc = '';
    }
    statusDescElement.textContent = statusDesc;
    
    // 设置状态操作按钮
    let actionButtons = '';
    switch(orderInfo.status) {
        case '待付款':
            actionButtons = `
                <button class="action-btn secondary" onclick="cancelOrder(${orderInfo.id})">
                    <i class="layui-icon layui-icon-close"></i>取消订单
                </button>
                <button class="action-btn primary" onclick="payOrder(${orderInfo.id})">
                    <i class="layui-icon layui-icon-rmb"></i>立即付款
                </button>
            `;
            break;
        case '已付款':
            actionButtons = `
                <button class="action-btn warning" onclick="remindShipping(${orderInfo.id})">
                    <i class="layui-icon layui-icon-tips"></i>提醒发货
                </button>
            `;
            break;
        case '已发货':
            actionButtons = `
                <button class="action-btn secondary" onclick="viewLogistics(${orderInfo.id})">
                    <i class="layui-icon layui-icon-release"></i>查看物流
                </button>
                <button class="action-btn primary" onclick="confirmReceive(${orderInfo.id})">
                    <i class="layui-icon layui-icon-ok"></i>确认收货
                </button>
            `;
            break;
        case '已完成':
            actionButtons = `
                <button class="action-btn secondary" onclick="viewLogistics(${orderInfo.id})">
                    <i class="layui-icon layui-icon-release"></i>查看物流
                </button>
                <button class="action-btn primary" onclick="buyAgain(${orderInfo.id})">
                    <i class="layui-icon layui-icon-cart"></i>再次购买
                </button>
            `;
            break;
        case '已取消':
            actionButtons = `
                <button class="action-btn primary" onclick="buyAgain(${orderInfo.id})">
                    <i class="layui-icon layui-icon-cart"></i>再次购买
                </button>
            `;
            break;
    }
    statusActionsElement.innerHTML = actionButtons;
}

// 渲染订单进度
function renderOrderProgress() {
    // 设置进度条状态
    const statusMap = {
        '待付款': 0,
        '已付款': 1,
        '已发货': 2,
        '已完成': 3,
        '已取消': -1
    };
    
    const currentStep = statusMap[orderInfo.status];
    
    // 如果订单已取消，显示特殊样式
    if (currentStep === -1) {
        document.querySelectorAll('.progress-item').forEach(item => {
            item.classList.add('已取消');
        });
        document.querySelectorAll('.progress-line').forEach(line => {
            line.classList.add('已取消');
        });
        return;
    }
    
    // 设置已完成的步骤
    document.querySelectorAll('.progress-item').forEach((item, index) => {
        if (index <= currentStep) {
            item.classList.add('active');
        }
    });
    
    document.querySelectorAll('.progress-line').forEach((line, index) => {
        if (index < currentStep) {
            line.classList.add('active');
        }
    });
    
    // 设置时间
    document.getElementById('createTime').textContent = formatDate(orderInfo.createTime);
    
    if (orderInfo.payTime) {
        document.getElementById('payTime').textContent = formatDate(orderInfo.payTime);
    }
    
    if (orderInfo.shipTime) {
        document.getElementById('shipTime').textContent = formatDate(orderInfo.shipTime);
    }
    
    if (orderInfo.completeTime) {
        document.getElementById('completeTime').textContent = formatDate(orderInfo.completeTime);
    }
}

// 渲染收货信息
function renderAddressInfo() {
    const addressInfoElement = document.getElementById('addressInfo');
    const address = orderInfo.address;
    
    if (!address) {
        addressInfoElement.innerHTML = '<div class="empty-info">暂无收货信息</div>';
        return;
    }
    
    addressInfoElement.innerHTML = `
        <div class="address-info">
            <div class="receiver-info">
                <span class="receiver-name">${address.receiverName}</span>
                <span class="receiver-phone">${address.receiverPhone}</span>
            </div>
            <div class="address-detail">
                ${address.province} ${address.city} ${address.district} ${address.detailAddress}
            </div>
        </div>
    `;
}

// 渲染商品列表
function renderProductList() {
    const productListElement = document.getElementById('productList');
    
    if (!orderInfo.items || orderInfo.items.length === 0) {
        productListElement.innerHTML = `
            <tr>
                <td colspan="4" class="empty-info">暂无商品信息</td>
            </tr>
        `;
        return;
    }
    
    productListElement.innerHTML = orderInfo.items.map(item => `
        <tr>
            <td class="product-info-col">
                <div class="product-info">
                    <div class="product-image">
                        <img src="${item.imageUrl || './img/default-book.jpg'}" alt="${item.bookTitle}">
                    </div>
                    <div class="product-detail">
                        <h4>${item.bookTitle}</h4>
                        <p class="author">${item.bookAuthor || '未知作者'}</p>
                    </div>
                </div>
            </td>
            <td class="price-col">¥${item.price.toFixed(2)}</td>
            <td class="quantity-col">${item.quantity}</td>
            <td class="subtotal-col">¥${(item.price * item.quantity).toFixed(2)}</td>
        </tr>
    `).join('');
}

// 渲染订单信息
function renderOrderInfo() {
    const orderInfoElement = document.getElementById('orderInfo');
    
    // 支付方式
    let paymentMethodText = '';
    switch(orderInfo.paymentMethod) {
        case 'ONLINE':
            paymentMethodText = '在线支付';
            break;
        case 'COD':
            paymentMethodText = '货到付款';
            break;
        case 'ALIPAY':
            paymentMethodText = '支付宝';
            break;
        case 'WECHAT':
            paymentMethodText = '微信支付';
            break;
        case 'BANK':
            paymentMethodText = '银行卡';
            break;
        default:
            paymentMethodText = '未知';
    }
    
    orderInfoElement.innerHTML = `
        <div class="info-item">
            <span class="info-label">订单编号：</span>
            <span class="info-value">${orderInfo.orderNumber}</span>
        </div>
        <div class="info-item">
            <span class="info-label">创建时间：</span>
            <span class="info-value">${formatDate(orderInfo.createdAt)}</span>
        </div>
        <div class="info-item">
            <span class="info-label">支付方式：</span>
            <span class="info-value">${paymentMethodText}</span>
        </div>
        ${orderInfo.payTime ? `
        <div class="info-item">
            <span class="info-label">支付时间：</span>
            <span class="info-value">${formatDate(orderInfo.payTime)}</span>
        </div>
        ` : ''}
        ${orderInfo.shipTime ? `
        <div class="info-item">
            <span class="info-label">发货时间：</span>
            <span class="info-value">${formatDate(orderInfo.shipTime)}</span>
        </div>
        ` : ''}
        ${orderInfo.completeTime ? `
        <div class="info-item">
            <span class="info-label">完成时间：</span>
            <span class="info-value">${formatDate(orderInfo.completeTime)}</span>
        </div>
        ` : ''}
        ${orderInfo.remark ? `
        <div class="info-item">
            <span class="info-label">订单备注：</span>
            <span class="info-value">${orderInfo.remark}</span>
        </div>
        ` : ''}
    `;
}

// 渲染订单金额
function renderOrderAmount() {
    // 商品总价（不含运费）
    const totalPrice = orderInfo.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
    
    document.getElementById('totalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
    document.getElementById('deliveryFee').textContent = orderInfo.deliveryFee > 0 ? `¥${orderInfo.deliveryFee.toFixed(2)}` : '包邮';
    document.getElementById('finalPrice').textContent = `¥${orderInfo.totalAmount.toFixed(2)}`;
}

// 获取订单状态文本
function getStatusText(status) {
    switch(status) {
        case '待付款': return '待付款';
        case '已付款': return '待发货';
        case '已发货': return '待收货';
        case '已完成': return '已完成';
        case '已取消': return '已取消';
        default: return '未知状态';
    }
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '--';
    
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 取消订单
function cancelOrder(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确定要取消该订单吗？', {icon: 3, title:'提示'}, function(index){
            const loadingIndex = layer.load(2);
            
            ApiService.order.cancelOrder(orderId)
                .then(response => {
                    layer.close(loadingIndex);
                    
                    if (response.data) {
                        layer.msg('订单已取消', {icon: 1});
                        
                        // 重新加载订单详情
                        setTimeout(() => {
                            loadOrderDetail();
                        }, 1500);
                    }
                })
                .catch(error => {
                    layer.close(loadingIndex);
                    console.error("取消订单失败:", error);
                    layer.msg('取消订单失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 支付订单
function payOrder(orderId) {
    // 跳转到支付页面
    window.location.href = `./payment.html?orderId=${orderId}`;
}

// 提醒发货
function remindShipping(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        layer.msg('已提醒卖家尽快发货', {icon: 1});
    });
}

// 查看物流
function viewLogistics(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        ApiService.order.getOrderLogistics(orderId)
            .then(response => {
                layer.close(loadingIndex);
                
                if (response.data) {
                    const logistics = response.data;
                    
                    // 更新物流信息
                    document.getElementById('logisticsCompany').textContent = logistics.company;
                    document.getElementById('logisticsNumber').textContent = logistics.number;
                    
                    // 渲染物流轨迹
                    const timelineElement = document.getElementById('logisticsTimeline');
                    
                    if (logistics.traces && logistics.traces.length > 0) {
                        timelineElement.innerHTML = logistics.traces.map(trace => `
                            <div class="logistics-item">
                                <div class="logistics-time">${formatDate(trace.time)}</div>
                                <div class="logistics-info">${trace.content}</div>
                            </div>
                        `).join('');
                    } else {
                        timelineElement.innerHTML = '<div class="logistics-empty">暂无物流信息</div>';
                    }
                    
                    // 显示物流信息弹窗
                    layer.open({
                        type: 1,
                        title: '物流信息',
                        content: document.getElementById('logisticsPopup'),
                        area: ['500px', '400px']
                    });
                } else {
                    layer.msg('暂无物流信息', {icon: 0});
                }
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("获取物流信息失败:", error);
                layer.msg('获取物流信息失败，请重试', {icon: 2});
            });
    });
}

// 确认收货
function confirmReceive(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        
        layer.confirm('确认已收到商品？', {icon: 3, title:'提示'}, function(index){
            const loadingIndex = layer.load(2);
            
            ApiService.order.confirmReceive(orderId)
                .then(response => {
                    layer.close(loadingIndex);
                    
                    if (response.data) {
                        layer.msg('确认收货成功', {icon: 1});
                        
                        // 重新加载订单详情
                        setTimeout(() => {
                            loadOrderDetail();
                        }, 1500);
                    }
                })
                .catch(error => {
                    layer.close(loadingIndex);
                    console.error("确认收货失败:", error);
                    layer.msg('确认收货失败，请重试', {icon: 2});
                });
            
            layer.close(index);
        });
    });
}

// 再次购买
function buyAgain(orderId) {
    layui.use('layer', function() {
        const layer = layui.layer;
        const loadingIndex = layer.load(2);
        
        // 将商品添加到购物车
        const addPromises = orderInfo.items.map(item => 
            ApiService.cart.addToCart(item.book.id, item.quantity)
        );
        
        Promise.all(addPromises)
            .then(() => {
                layer.close(loadingIndex);
                layer.msg('已添加到购物车', {icon: 1});
                
                // 更新购物车数量
                if (AuthService.updateCartCount) {
                    AuthService.updateCartCount();
                }
                
                // 询问是否前往购物车
                layer.confirm('商品已添加到购物车，是否立即结算？', {icon: 1, title:'提示'}, function(index){
                    window.location.href = './cart.html';
                    layer.close(index);
                });
            })
            .catch(error => {
                layer.close(loadingIndex);
                console.error("添加到购物车失败:", error);
                layer.msg('添加到购物车失败，请重试', {icon: 2});
            });
    });
}